/**
 * 
 */

package com.chengyu.eyc.socket;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.chengyu.eyc.constant.EycConstants;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@Component
public class EycWebSocketHandler extends TextWebSocketHandler {

    private static ConcurrentHashMap<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        UserDetails userDetails = (UserDetails)session.getAttributes().get(EycConstants.USER_ID);
        if (userDetails != null) {
            sessionMap.remove(userDetails.getUsername());
            log.info("ws conn close, session {} out", userDetails.getUsername());
            log.info("ws conn {}", String.valueOf(sessionMap.size()));
        } else {
            log.warn("ws conn close with visitor id={}", session.getId());
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.debug("Opened new session in instance " + this);
        UserDetails userDetails = (UserDetails)session.getAttributes().get(EycConstants.USER_ID);
        if (userDetails != null) {
            sessionMap.put(userDetails.getUsername(), session);
            log.info("ws conn established {}", userDetails.getUsername());
            log.info("ws conn {}", String.valueOf(sessionMap.size()));
        } else {
            log.warn("ws conn established with visitor id={}", session.getId());
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 组装返回的Echo信息
        // String echoMessage = this.echoService.echo(message.getPayload());
        // log.debug(MessageFormat.format("Echo message \"{0}\"", echoMessage));

        log.info("ws msg={}", message.toString());
        log.info("ws msg payload={}", message.getPayload());
        if (!session.isOpen()) {
            return;
        }

        // 解析信息
        UserDetails userDetail = (UserDetails)session.getAttributes().get(EycConstants.USER_ID);
        if (userDetail == null) {
            return;// 游客忽略
        }
        if (StrUtil.isBlank(message.getPayload())) {
            return;
        }

        TextMessage textMsg = new TextMessage(message.getPayload());
        session.sendMessage(textMsg);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.close(CloseStatus.SERVER_ERROR);
        log.debug("Info: WebSocket connection closed.");
    }

    public void sendFanoutMessage(String message) {
        try {
            for (Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
                handleTextMessage(entry.getValue(), new TextMessage(message));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
